package com.ezcolour.ticket.web.controller;

import com.ezcolour.ticket.base.BaseController;
import com.ezcolour.ticket.base.BaseException;
import com.ezcolour.ticket.bean.JwtProperties;
import com.ezcolour.ticket.common.model.AuthRequest;
import com.ezcolour.ticket.common.model.AuthResponse;
import com.ezcolour.ticket.model.Member;
import com.ezcolour.ticket.service.MemberService;
import com.ezcolour.ticket.support.BizExceptionEnum;
import com.ezcolour.ticket.util.JwtTokenUtil;
import com.ezcolour.ticket.util.PasswordUtil;
import com.ezcolour.ticket.web.global.GlobalCache;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.CookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  用户登录注册
 *
 * @author rhp
 * @date 2017-08-23 9:23
 */
@RestController
@RequestMapping("/web/api")
public class MemberController extends BaseController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtProperties jwtProperties;
    
    /**
     * 用户登录
     */
    @ApiOperation("web用户登录")
    @RequestMapping(value = "/auth", method = RequestMethod.POST)
    public ResponseEntity<?> login(AuthRequest authRequest) {
        System.out.println(authRequest.getUserName()+";"+authRequest.getPassword());
        boolean validate = memberService.validate(authRequest);
        if(validate){
            final String randomKey = jwtTokenUtil.getRandomKey();
            final String token = jwtTokenUtil.generateToken(authRequest.getUserName(), randomKey);
            return ResponseEntity.ok(new AuthResponse(token, randomKey));
        }else{
            throw new BaseException(BizExceptionEnum.AUTH_REQUEST_ERROR);
        }
    }

    /**
     * web用户注册
     */
    @ApiOperation("web用户注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseEntity<?> register(Member member) {
        Member find = memberService.findByPhoneNumber(member.getPhoneNumber());
        if(find!=null){
            throw new BaseException(BizExceptionEnum.USER_ALREADY_REG);
        }
        String salt = PasswordUtil.getSalt();
        String password = PasswordUtil.generate(salt, member.getPassword());
        member.setSalt(salt);
        member.setPassword(password);
        memberService.save(member);
        return ResponseEntity.ok("success");
    }


    /**
     * 查看当前用户的登录cookie
     */
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public ResponseEntity<?> findUsers(HttpServletRequest request) {
        ConcurrentHashMap<String, CookieStore> cookies = GlobalCache.user_login_cookies.get(getLoginUserName(request));
        if(cookies==null || cookies.size()<=0){
            throw new BaseException(BizExceptionEnum.AUTH_COOKIE_ERROR);
        }
        List<String > list = new ArrayList<String>();
        Iterator iter = cookies.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            list.add(entry.getKey().toString());
        }
        return ResponseEntity.ok(list);
    }


    public String getLoginUserName(HttpServletRequest request){
        final String requestHeader = request.getHeader(jwtProperties.getHeader());
        String authToken = requestHeader.substring(7);
        return jwtTokenUtil.getUsernameFromToken(authToken);
    }
}
